var express = require('express');
var router = express.Router();
var db = require("../db/db.js");
var multer = require("multer");
var path = require("path");
var util = require('./util.js');

// handle upload storage strategy
var upload = multer({
	storage: multer.diskStorage({
		destination: function(req, file, cb) { // set upload directory
			cb(null, 'public/uploads/user/');
		},
		filename: function(req, file, cb) { // set upload filename
			cb(null, Date.now() + path.extname(file.originalname));
		}
	})
});

/* GET users listing. */
router.get('/', function(req, res, next) {
	res.render("user/index", {
		sub_title: "User Management"
	});
});

//  GET to page with data
router.get('/list', function(req, res) {
	var json = db.users.findAll();
	res.render("user/list", {
		items: json,
		layout: false
	});
});

//  GET to page
router.route('/add')
	.get(function(req, res) {
		// req.body will hold the text fields, if there were any
		res.render("user/add", {
			layout: false
		})
	})
	.post(upload.single('photo'), function(req, res) {
		// req.body will hold the text fields, if there were any
		var msg = "";
		db.users.add(req.body.nickname, req.body.username, req.body.password, req.body.email, req.file.filename);
		res.render('tips/success');
	});

// POST -> req.body.xxx
router.post('/del', function(req, res) {
	var id = req.body.id;
	var user = db.users.findByIdNoCb(id)
	db.users.deleteById(id);
	util.deleteFile(user.icon);
	res.send("delete success");
});

// POST -> req.body.xxx
router.post('/edit', function(req, res) {
	var user = {
		id: req.body.id,
		username: req.body.username,
		email: req.body.email,
		nickname: req.body.nickname
	}
	db.users.update(user)
	res.send("edit success");
});

// GET请求 :xxx -> req.params.xxx
router.get('/detail/:id', function(req, res) {
	var item = db.users.findByIdNoCb(req.params.id);
	res.send(item);
});

module.exports = router;